# -*- coding:utf-8 -*-
import random
import hashlib
import httpclient
import json
url='openapi.youdao.com'
appkey='RRWfZ7qiSgyJvjKIx4CxrhbYbuUvbSyo'

def getParams(q,appid,fromText,toText):
    salt=random.randint(0,9)
    source = (appid+q+str(salt)+appkey).encode('utf-8')
    md5=hashlib.md5(source)
    sign=md5.hexdigest()
    params=dict()
    params['q']=q.encode('utf-8')
    params['from']=fromText
    params['to']=toText
    params['appKey']=appid
    params['salt']=salt
    params['sign']=sign.upper()
    return params


def getIcon():
    icon={}
    icon['path']='icon.png'
    return icon


def getItem(title, subtitle):
    if title:
        item={}
        item['title']=title
        item['subtitle']=subtitle
        item['icon']=getIcon()
        return item
    else:
        return None


def getPhonetic(data):
    uk=data.get('uk-phonetic')
    us=data.get('us-phonetic')
    phonetic=''
    if uk:
        phonetic+='英音：'+uk
    if us:
        if len(phonetic)>0:
            phonetic+=' | '
        phonetic+='美音：'+us

    if(len(phonetic)>0):
        return getItem(phonetic,'发音')
    pass


def getEmptyItem():
    return getItem('没结果','这个单词有道词典都查不出来')


def getWebMean(webs):
    if webs:
        items=list()
        for web in webs:
            values=web['value']
            items.append(getItem(values,'网络释义'))
        return items
    else:
        return None



def getItemList(json_str):
    data=json.loads(json_str)
    print(data)
    items=list()
    errorCode=data['errorCode']
    basic=data.get('basic')
    if errorCode=='0' and basic:
        items.append(getPhonetic(basic))

        explains = basic.get('explains')
        if len(explains) == 0:
            items.append(getEmptyItem())
        else:
            for explain in explains:
                items.append(getItem(explain,'简明释义'))
        webs = data['web']
        items.extend(getWebMean(webs))

        transaction =data['translation']
        items.append(getItem(transaction[0],'翻译'))
        return items
    return list()




def getTransaction(q,appid,fromText='auto',toText='auto'):
    params=getParams(q,appid,fromText,toText)
    print(params)
    response=httpclient.post(url,params)
    items=list()
    if response.status == 200:
        items=getItemList(response.read())
    else:
        items.append('网络不给力啊，等一会吧','')
    if len(items) == 0:
        items.append(getEmptyItem())
    jsonbean={}
    itemslIst=list()
    itemslIst.extend(filter(lambda x:x is not None,items))
    print('最终',itemslIst)
    jsonbean['items']=itemslIst
    #return json.dumps(jsonbean)
    return itemslIst

def query(q,appid='4578669b7f1a2342'):
    str=getTransaction(q,appid)

    return str

if __name__ == '__main__':
    print(query('combo'))